package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class QuanZiService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private PicUploadService picUploadService;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 好友动态
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult queryPublishList(Integer page, Integer pagesize/*, String token*/) {
        //1.先将返回的结果部分填充
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        //2.校验token
        /*User user = userService.queryUserByToken(token);
        if(user==null){
           return pageResult;
        }*/   //拦截器原因
        User user = UserThreadLocal.get();
        //3.调用dubbo中的quanZiApi查询publish,以及调用userInfoService中的queryUserInfoList查询userInfo
        PageInfo<Publish> pageInfo = quanZiApi.queryPublishList(user.getId(), page, pagesize);
        //4.new 一个quanzivo的集合
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        //5.循环遍历,将publish中的信息填充至quanzivo,这里只补全了quanzivo的部分信息
        List<Publish> records = pageInfo.getRecords();

        for (Publish publish : records) {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            UserInfo userInfo = userInfoService.queryTodayBestById(publish.getUserId());
            BeanUtil.copyProperties(userInfo, quanZiVo, "id");
            quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
            quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
            quanZiVo.setCommentCount(0); //TODO 评论数
            quanZiVo.setDistance("1.2公里"); //TODO 距离
            quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //TODO 是否点赞（1是，0否）
            quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //TODO 点赞数
            quanZiVo.setHasLoved(0); //TODO 是否喜欢（1是，0否）
            quanZiVo.setLoveCount(0); //TODO 喜欢数
            quanZiVoList.add(quanZiVo);
        }
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 发布动态
     *
     * @param textContent
     * @param location
     * @param latitude
     * @param longitude
     * @param multipartFile
     * @return
     */
    public String savePublish(String textContent,
                              String location,
                              String latitude,
                              String longitude,
                              MultipartFile[] multipartFile) {

        //查询当前的登录信息
        User user = UserThreadLocal.get();

        //然后根据userId检验是否冻结
        String freezeRange = redisTemplate.opsForValue().get("USER_FREEZE_RANGE_" + user.getId());
        if (ObjectUtil.isNotEmpty(freezeRange) && freezeRange.equals("3")){
            return null;
        }

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);

        List<String> picUrls = new ArrayList<>();
        //图片上传
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            picUrls.add(picUploadResult.getName());
        }

        publish.setMedias(picUrls);
        return this.quanZiApi.savePublish(publish);
    }

    /**
     * 推荐动态
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult queryRecommendPublishList(Integer page, Integer pagesize) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);

        PageInfo<Publish> pageInfo = quanZiApi.queryRecommendPublishList(user.getId(), page, pagesize);
        List<Publish> records = pageInfo.getRecords();

        List<QuanZiVo> quanZiVoList = new ArrayList<>();

        for (Publish publish : records) {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            UserInfo userInfo = userInfoService.queryTodayBestById(publish.getUserId());
            BeanUtil.copyProperties(userInfo, quanZiVo, "id");
            quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
            quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
            quanZiVo.setCommentCount(0); //TODO 评论数
            quanZiVo.setDistance("1.2公里"); //TODO 距离
            quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //TODO 是否点赞（1是，0否）
            quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //TODO 点赞数
            quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0); //TODO 是否喜欢（1是，0否）
            quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(quanZiVo.getId()))); //TODO 喜欢数
            quanZiVoList.add(quanZiVo);
        }
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 点赞
     *
     * @param publishId
     * @return
     */
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.likeComment(user.getId(), publishId);//没点过赞
        if (result) {
            return quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    /**
     * 取消点赞
     *
     * @param publishId
     * @return
     */
    public Long dislikeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.disLikeComment(user.getId(), publishId);//点过赞
        if (result) {
            return quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    /**
     *喜欢
     * @param publishId
     * @return
     */
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.loveComment(user.getId(), publishId);//没点过赞
        if (result) {
            return quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }

    /**
     * 取消喜欢
     * @param publishId
     * @return
     */
    public Long unLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.disLoveComment(user.getId(), publishId);//点过赞
        if (result) {
            return quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }

    /**
     * 查询单条动态
     * @param publishId
     * @return
     */
    public QuanZiVo queryById(String publishId) {
        User user = UserThreadLocal.get();
        Publish publish = quanZiApi.queryPublishById(publishId);
        if (null == publish) {
            return null;
        }
        QuanZiVo quanZiVo = new QuanZiVo();
        quanZiVo.setId(publish.getId().toHexString());
        quanZiVo.setTextContent(publish.getText());
        quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
        quanZiVo.setUserId(publish.getUserId());
        quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
        UserInfo userInfo = userInfoService.queryTodayBestById(publish.getUserId());
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //TODO 是否点赞（1是，0否）
        quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //TODO 点赞数
        quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0); //TODO 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(quanZiVo.getId()))); //TODO 喜欢数

        return quanZiVo;
    }

    /**
     * 查询评论列表
     *
     * @param page
     * @param pageSize
     * @param publishId
     * @return
     */
    public PageResult queryCommentsList(Integer page, Integer pageSize, String publishId) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();
        //根据publishId将该动态下的所有的评论找出来
        PageInfo<Comment> pageInfo = quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        //利用找出来的评论将评论的用户id找出来
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        //利用用户id将所有的评论过的用户找出来
       /* QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);*/
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userIds);
        //填充信息
        List<CommentVo> commentVos = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            //是否点赞
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));


            for (UserInfo userInfo : userInfos) {
                if (ObjectUtil.equals(record.getUserId(), userInfo.getUserId())) {
                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            commentVos.add(commentVo);
        }
        pageResult.setItems(commentVos);
        return pageResult;
    }

    /**
     * 发表评论
     * @param publishId
     * @param content
     * @return
     */
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();

        //然后根据userId检验是否冻结
        String freezeRange = redisTemplate.opsForValue().get("USER_FREEZE_RANGE_" + user.getId());
        if (ObjectUtil.isNotEmpty(freezeRange) && freezeRange.equals("2")){
            return false;
        }

        return this.quanZiApi.saveComment(user.getId(), publishId, content);
    }

    /**
     * 查询个人相册
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Publish> pageInfo = quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if(ObjectUtil.isEmpty(records)){
            return pageResult;
        }

        List<QuanZiVo> quanZiVoList = new ArrayList<>();

        for (Publish publish : records) {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            UserInfo userInfo = userInfoService.queryTodayBestById(publish.getUserId());
            BeanUtil.copyProperties(userInfo, quanZiVo, "id");
            quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
            quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
            quanZiVo.setCommentCount(0); //TODO 评论数
            quanZiVo.setDistance("1.2公里"); //TODO 距离
            quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //TODO 是否点赞（1是，0否）
            quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); //TODO 点赞数
            quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0); //TODO 是否喜欢（1是，0否）
            quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(quanZiVo.getId()))); //TODO 喜欢数
            quanZiVoList.add(quanZiVo);
        }

        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 来访的用户
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        //查询所有造访过我的用户
        List<Visitors> visitorsList = visitorsApi.queryMyVisitor(user.getId());
        //得到这些用户的id
        List<Object> visitorUserIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        //通过用户id查询到用户
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(visitorUserIds);
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        //循环遍历这两这集合
        for (Visitors visitors : visitorsList) {
            for (UserInfo userInfo : userInfos) {
               // if(visitors.getVisitorUserId()==userInfo.getUserId()){
                if(ObjectUtil.equals(visitors.getVisitorUserId(),userInfo.getUserId())){
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitors.getScore().intValue());
                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }
}